package org.cos.generation.util.agorithm;

import java.util.Iterator;
import java.util.List;

import org.cos.generation.epda.State;
import org.cos.generation.epda.State.Transition;

public class MergeState {

	private State[] states;
	
	private int[] stateRoot;
	
	private boolean merged[];
	
	private int size;
	
	public void mergeState(State[] states, int[] stateRoot) {
		this.states = states;
		this.stateRoot = stateRoot;
		this.size = states.length;
		this.merged = new boolean[size];
		for (int i = 0; i < size; i++) {
			mergeTransition(i);
		}
	}
	
	private void mergeTransition(int index) {
		if (states[index]!= null && !merged[index]) {
			List<Transition> transitions = 
				states[index].getTransitions();
			int head = index == stateRoot[index] ? 
					index : stateRoot[index];
			for (Iterator<Transition> it = transitions.iterator();
					it.hasNext();) {
				Transition trans = it.next();
				int oldTail = trans.getTailIndex();
				int newTail = stateRoot[oldTail];
				if (trans.getMethod() == null && newTail == head) {
					it.remove();
				} else if (newTail != oldTail) {
					trans.setTailIndex(newTail);
				}
			}
			if (head != index) {
				mergeTransition(head);
				states[head].getTransitions().addAll(transitions);
				states[index] = null;
			}
			merged[index] = true;
		}
	}
	
	
}